<template>
  <a-drawer
    :width="340"
    :mask-closable="false"
    :visible="visible"
    unmount-on-close
    :ok-loading="loading"
    @cancel="close"
    @ok="onOk"
  >
    <template #title>
      {{ title }}
    </template>
    <div>
      <a-form
        ref="form"
        layout="vertical"
        :model="form"
        :disabled="disabled"
        :style="{width:'100%'}">
        <a-form-item
          field="name"
          label="角色名"
          :rules="[{required: true, message:'请输入角色名'}]">
          <a-input v-model="form.name" placeholder="请输入角色名..." allow-clear />
        </a-form-item>
        <a-form-item
          field="code"
          label="角色编码"
          :rules="[{required: true, message:'请输入角色编码'}]">
          <a-input v-model="form.code" placeholder="请输入角色编码..." allow-clear />
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script>

import useLoading from "@/hooks/loading";
import { Operation } from "@/types/global";
import {create, findById, update} from "@/api/modules/system/role";

const { loading, setLoading } = useLoading()

export default {
  name: 'RoleBoard',
  emits: ['ok'],
  data() {
    return {
      title: '',
      operation: '',
      visible: false,
      loading,
      disabled: false,
      form: {},
    }
  },
  methods: {
    async open(id, operation) {
      if (id) {
        const { data } = await findById(id)
        const { name, code } = data
        this.form = {
          id, name, code
        }
      }
      this.title = operation
      this.operation = operation
      this.disabled = Operation.PREVIEW === operation
      this.visible = true
    },
    close() {
      this.visible = false
      this.title = ''
      this.disabled = false
      this.$refs.form.resetFields()
      this.form = {}
    },
    onOk() {
      if (this.operation === Operation.PREVIEW) {
        this.close()
        return
      }
      this.$refs.form.validate(async errors => {
        if (!errors) {
          try {
            setLoading(true)
            if (this.operation === Operation.CREATE) {
              await create(this.form)
            } else if (this.operation === Operation.UPDATE) {
              await update(this.form)
            }
            this.close()
            this.$emit('ok')
          } finally {
            setLoading(false)
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
